package com.xci.sys.controller;

import com.xci.core.annotation.Authorize;
import com.xci.core.base.RestMessage;
import com.xci.core.base.WebController;
import com.xci.core.domain.OnlineUserModel;
import com.xci.core.exceptions.EntityNotFoundException;
import com.xci.core.helper.Helper;
import com.xci.core.web.JsonGrid;
import com.xci.sys.service.OnlineUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 在线用户控制器
 */
@Authorize
@Slf4j
@Controller
@RequestMapping("/sys/onlineUser")
public class OnlineUserController extends WebController {
    /**
     * 系统在线用户服务
     */
    @Resource
    private OnlineUserService onlineUserService;

    //region 页面视图

    /**
     * 在线用户首页
     */
    @GetMapping
    @Authorize(code = "sys.onlineUser")
    public String index() {
        return "sys/onlineuser/index";
    }

    /**
     * 在线用户详细页面
     */
    @GetMapping("/details")
    public String details(String id, ModelMap map) {
        OnlineUserModel entity = onlineUserService.get(id);
        if (entity == null) throw new EntityNotFoundException(id);
        map.put("entity", entity);
        return "sys/onlineuser/details";
    }

    //endregion

    //region 数据处理

    /**
     * 在线用户表格数据
     */
    @ResponseBody
    @GetMapping("/grid")
    @Authorize(code = "sys.onlineUser.select")
    public JsonGrid grid(String name) {
        return RestMessage.grid(onlineUserService.query(name));
    }

    /**
     * 激活当前用户
     */
    @ResponseBody
    @PostMapping("/active")
    public RestMessage active() {
        onlineUserService.active(getCurrentUser());
        return RestMessage.success();
    }

    /**
     * 注销在线用户
     */
    @ResponseBody
    @PostMapping("/logoff")
    @Authorize(code = "sys.onlineUser.logoff")
    public RestMessage logoff(String ids) {
        for (String id : Helper.splitToArray(ids)) {
            onlineUserService.logoff(id);
        }
        return RestMessage.success();
    }

    //endregion
}
